package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@Service
public class VideoApiImpl implements VideoApi {
    //注入 MongoTemplate
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 小视屏上传
     *
     * @param video
     */
    @Override
    public void add(Video video) {
        video.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(video);//todo 用save行不行

    }

    /**
     * 分页查询小视屏
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findPage(Long page, Long pageSize) {
        //构建分页查询条件对象
        Query query = new Query();

        //统计总数
        long count = mongoTemplate.count(query, Video.class);
        PageResult pageResult = new PageResult();
        if (count > 0) {
            //构建分页
            query.skip((page - 1) * pageSize).limit(pageSize.intValue());

            query.with(Sort.by(Sort.Order.desc("created"))); //按照发布时间降序
            //查询分页
            List<Video> videoList = mongoTemplate.find(query, Video.class);

            //构建分页对象
            pageResult = PageResult.pageResult(page, pageSize, videoList, count);

        }
        //返回
        return pageResult;
    }

    /**
     * 关注用户
     *
     * @param followUser
     */
    @Override
    public void focusUser(FollowUser followUser) {
        //调用mongoTemplate添加数据
        followUser.setCreated(System.currentTimeMillis()); //关注时间
        mongoTemplate.save(followUser);


    }

    /**
     * 取消关注用户
     *
     * @param followUser
     */
    @Override
    public void removeUser(FollowUser followUser) {
        //构建删除条件
        Query query = new Query(Criteria.where("userId").is(followUser.getUserId())
                .and("followUserId").is(followUser.getFollowUserId()));

        //调用mongoTemplate删除数据
        mongoTemplate.remove(query,FollowUser.class);

    }
}
